package lol.clann.minecraft.springboot.plugin.bukkit.command;

import com.google.common.base.Joiner;
import com.ruoshui.utils.java.exception.ExceptionUtils;
import lol.clann.minecraft.springboot.api.bukkit.utils.PlayerUtils;
import lol.clann.minecraft.springboot.api.context.SpringContext;
import lol.clann.minecraft.springboot.api.model.LazyField;
import lombok.extern.slf4j.Slf4j;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 *
 * @author pyz
 * @date 2019/5/6 7:51 PM
 */
@Slf4j
public class CommandAdapter extends Command {
    public static final Joiner joiner = Joiner.on(" ");
    private CommandDispatcher dispatcher;
    private static LazyField<PlayerUtils> playerUtils = LazyField.of(() -> SpringContext.getBean(PlayerUtils.class));

    public CommandAdapter(CommandDispatcher rootDispatcher, String name, String description, String usageMessage, List<String> aliases) {
        super(name, description, usageMessage, aliases);
        this.dispatcher = rootDispatcher;
    }

    @Override
    public boolean execute(CommandSender commandSender, String s, String[] strings) {
        try {
            return dispatcher.dispatch(commandSender, CommandContext.parse(s, strings), 0);
        } catch (Throwable e) {
            resolveException(commandSender, e, s + " " + joiner.join(strings));
            return true;
        }
    }

    @Override
    public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
        return dispatcher.tabComplete(sender, alias, args);
    }

    public static void resolveException(CommandSender commandSender, Throwable e, String fullCommand) {
        CommandException commandException = ExceptionUtils.unwrap(e, CommandException.class);
        if (commandException != null) {
            commandSender.sendMessage(ChatColor.DARK_RED + commandException.getMessage());
            return;
        }
        UnsupportedOperationException unsupportedOperationException = ExceptionUtils.unwrap(e, UnsupportedOperationException.class);
        if (unsupportedOperationException != null) {
            String message = StringUtils.hasText(unsupportedOperationException.getMessage()) ? unsupportedOperationException.getMessage() : "该指令功能尚未开发完成!";
            commandSender.sendMessage(ChatColor.DARK_RED + message);
            return;
        }
        Throwable realException = ExceptionUtils.unwrap(e);
        if (commandSender instanceof Player) {
            playerUtils.get().printException((Player) commandSender, realException);
        }
        LOGGER.error("指令执行失败:/" + fullCommand, realException);
    }
}
